package com.yuanluludev.lib_x5web

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient
import com.tencent.smtt.sdk.WebChromeClient
import kotlinx.android.synthetic.main.activity_x5_web_video.*

/**
 * yuanLulu
 * 用于展示视频
 */
class VideoActivity : BaseWebViewActivity() {

    private var fullScreenLayer: View? = null

    companion object {
        private const val WEB_URL = "web_url"
        private const val TITLE_TEXT = "title_text"

        @JvmStatic
        fun jump(context: Context, webUrl: String, titleText: String = "") {
            context.startActivity(Intent(context, VideoActivity::class.java).apply {
                putExtra(WEB_URL, webUrl)
                putExtra(TITLE_TEXT, titleText)
            })
        }
    }

    override fun onResume() {
        super.onResume()
        // 如果之前处于全屏状态，重新进入后需要再次调用全屏
        fullScreenLayer?.let{
            fullScreen(it)
        }
    }

    override fun initWebView() {
        super.initWebView()
        mWebView?.webChromeClient = object : WebChromeClient() {
            override fun onShowCustomView(view: View, customViewCallback: IX5WebChromeClient.CustomViewCallback) {
                // view 为内核生成的全屏视图，需要添加到相应的布局位置（如：全屏幕）
                // customViewCallback 用于主动控制全屏退出
                windowManager?.addView(view, WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_APPLICATION))
                fullScreen(view)
                fullScreenLayer = view
            }

            override fun onHideCustomView() {
                windowManager.removeViewImmediate(fullScreenLayer)
                fullScreenLayer = null
            }
        }

        val webUrl = intent?.getStringExtra(WEB_URL) ?: ""
        if (!TextUtils.isEmpty(webUrl)) {
            mWebView?.loadUrl(webUrl)
        }

    }

    private fun fullScreen(view: View) {
        view.systemUiVisibility = (View.SYSTEM_UI_FLAG_LOW_PROFILE
                or  View.SYSTEM_UI_FLAG_FULLSCREEN
                or  View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or  View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or  View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)
    }

    override fun getLayoutResId() = R.layout.activity_x5_web_video

    override fun getContainerID() = R.id.rlContainer

    override fun initEvents() {
        val titleText = intent?.getStringExtra(TITLE_TEXT) ?: ""
        if (!TextUtils.isEmpty(titleText)) {
            titleBar?.setTitleText(titleText)
        }
    }

    override fun setTitleText(title: String) {
        val titleText = intent?.getStringExtra(TITLE_TEXT) ?: ""
        if (TextUtils.isEmpty(titleText)) {
            titleBar?.setTitleText(title)
        }
    }

}